import React from 'react'
import { TreeList, info, success, RadioGroup, DateSelect, Checkbox, error, TitleBar, Button, Input, Select, SelectList } from '../../../ui-components'
import {FieldBox} from '../../../ui-components/form'
import style from './style.filling'
import { connect } from 'react-redux'
import { ROOT_TEAM } from '../../../constants'
import util from '../../../util'
import DatePicker from 'react-date-picker'
import moment from 'moment'
import { makeTeamTree } from '../../team/TeamManage'
import { bindActionCreators } from 'redux'
import { fetchTeamData } from '../../../actions/team.action'
import { fetchProfileTemplateFields } from '../../../actions/system.action'
import { fetchAtList, clearAtList } from '../../../actions/home.action'
import {updateProfileTemplateFieldDetailCore} from '../../../actions/profileFieldDetail.action'
import * as hrAction from '../../../actions/onboarding.hr.action'
import validate from '../../../libs/validate'

export default
@connect(({ onboardingFlowsHr, team, onboardingTemplates, app, profileTemplate }) => ({ onboardingTemplates, app, profileTemplate, team, onboardingFlowsHr }), dispatch => ({actions: bindActionCreators({ ...hrAction, fetchTeamData, fetchProfileTemplateFields, fetchAtList, clearAtList, updateProfileTemplateFieldDetailCore }, dispatch)}))
class Filling extends React.Component {

  fields = {
    fullName: '', 
    emailAddress: '', 
    //citizenId: '', 
    mobilePhone: '', 
    employeeId: '',
    enrollDate: '', 
    teamId: '', 
    onboardingTemplateId: '', 
    jobTitle: '', 
    jobLevel: '',
    reporterUserId: '',
    contractType: '',
    gender: '',
    isTeamAdmin: 0,
    roleIds: []
  }

  state = {
    profileTemplateId: '', 
    searchReportor: '',
    showDatePicker: false,
    contractTypes: [
      {
       label: '实习',
       value: 1
      },
      {
        label: '兼职',
        value: 2
      },
      {
        label: '全职',
        value: 3
      }
    ],
    fields: this.fields,
    jobTitleOpts: [],
    jobLevelOpts: [],
  }

  componentWillReceiveProps(props) {
    if (!util.isNull(props.onboardingFlowsHr.roles)) {
      this.setState({
        fields: {
          
          ...this.state.fields,
          roleIds: [
            {
              idValue: util.find(props.onboardingFlowsHr.roles, role => role.roleName == 'staff').roleId
            }
          ] 
        }
      })
    }
  }

  componentDidMount() {
    this.props.actions.fetchOnboardingTemplates()
    this.props.actions.fetchProfileTemplateFields()
    this.props.actions.fetchTeamData()
    this.props.actions.fetchRole()

    this.props.actions.updateProfileTemplateFieldDetailCore({
      configType: 1
    }, (opts) => {
      this.setState({
        jobTitleOpts: opts,
      });
    });

    this.props.actions.updateProfileTemplateFieldDetailCore({
      configType: 2
    }, (opts) => {
      this.setState({
        jobLevelOpts: opts,
      });
    });

  }

  handleContractTypeChange(e) {
    const contractType = e.target.value
    this.setState({
      contractTypes: this.state.contractTypes.map(type => {
        if (type.value == contractType) {
          return {
            ...type,
            checked: true
          }
        } else {
          return {
            ...type,
            checked: false
          }
        }
      })
    })
    this.updateField({
      contractType: e.target.value
    })
  }

  toggleRoles(roleId) {
    if (this.state.fields.roleIds.some(r => r.idValue == roleId)) {
      this.updateField({
        roleIds: this.state.fields.roleIds.filter(r => r.idValue != roleId)
      })
    } else {
      this.updateField({
        roleIds: [
          ...this.state.fields.roleIds,
          {
            idValue: roleId
          }
        ]
      })
    }
  }

  handleSelectReportor(i) {

    const item = this.props.app.atList[this.state.searchReportor][i];

    this.updateField({
      reporterUserId: item.userId
    })

    this.setState({
      searchReportor: item.fullName
    })

  }

  handleChangeSelectOnboardingTemplate(e) {
    const { value: onboardingTemplate } = e.target
    if (!util.isNull(onboardingTemplate)) {
      const { profileTemplateId } = this.props.onboardingTemplates.list.filter(v => v.onboardingTemplateId == onboardingTemplate)[0]
      this.setState({
        profileTemplateId
      })
      this.props.actions.fetchProfileTemplateFields(profileTemplateId)
    } else {
      this.updateField({
        jobLevel: '',
        jobTitle: ''
      })
    }

    this.updateField({
      onboardingTemplateId: e.target.value
    })
  }

  handleSelectTeam(team) {
    this.updateField({
      teamId: team.teamId
    })
  }

  renderOnboardingTemplate() {
    const { list=[] } = this.props.onboardingTemplates
    return (
      <Select 
        required
        value={this.state.fields.onboardingTemplateId}
        onChange={::this.handleChangeSelectOnboardingTemplate}
        label={'入职模板'}
      >
        <option value="">选择入职模板...</option>
        {
          (list || []).map((v, i) => (
            <option key={i} value={v.onboardingTemplateId}>{ v.displayName }</option>
          ))
        }
      </Select>
    )
  }

  renderTeams() {
    let { teams } = this.props.team
    const rootTeam = makeTeamTree(teams)[0]
    return (
      <TreeList
        onClick={::this.handleSelectTeam}
        root={rootTeam}
        placeholder="选择团队..."
        label={'团队'}
        required
      />
    )
  }

  renderJobTitle(jobTitle) {
    if (!jobTitle) return null
    return (
      <Select label={'职位'} value={this.state.fields.jobTitle} onChange={(e) => this.updateField({ jobTitle: e.target.value })}>
        <option value="">选择职位...</option>
        {
          this.state.jobTitleOpts.map((v, i) => (
            <option key={i} value={v.orgPickOptionId}>{ v.optionValue }</option>
          ))
        }
      </Select>
    )
  }

  renderJobLevel(jobLevel) {
    if (!jobLevel) return null
    return (
      <Select label={'职级'} value={this.state.fields.jobLevel} onChange={e => this.updateField({ jobLevel: e.target.value })}>
        <option value="">选择职级...</option>
        {
          this.state.jobLevelOpts.map((v, i) => (
            <option key={i} value={v.orgPickOptionId}>{ v.optionValue }</option>
          ))
        }
      </Select>
    )
  }

  searchReportor(e) {
    this.setState({
      searchReportor: e.target.value
    })
    this.props.actions.fetchAtList({ keyword: e.target.value, type: 2})
  }

  renderReportLine() {
    return (
      <div className={style.reportLine}>
        <Input value={this.state.searchReportor} onChange={::this.searchReportor} label="设置汇报对象"/>
        <SelectList
          handleSelect={::this.handleSelectReportor}
          className={style.searchReportorList}
          show={!util.isNull(this.state.searchReportor)}
          data={this.props.app.atList[this.state.searchReportor]}
          item={
            ({ avatarUrl, fullName, jobTitle }, attrs={}) => (
              <li {...attrs}>
                <img src={avatarUrl}/>
                <span>{ fullName }</span>
                {
                  jobTitle?
                <span>({ jobTitle })</span>: null
                }
              </li>
            )
          }
        />
      </div>
    )
  }

  updateField(field) {
    this.setState({
      fields: {
        ...this.state.fields,
        ...field
      }
    })
  }

  handleInput(name) {
    return e => {
      this.updateField({
        [name]: e.target.value
      })
    }
  }

  renderEnrollDate() {
    return (
      <div style={{ position: 'relative' }}>
        <DateSelect
          required
          label="入职日期"
          time={this.state.fields.enrollDate && moment(+this.state.fields.enrollDate).format('YYYY-MM-DD')}
          onChange={time => this.updateField({ enrollDate: time })}
        />
        <p style={{ color: '#8ca9c5', fontSize: '12px', left: '141px', top: '40px', position: 'absolute' }}>入职日期之后，员工才能激活帐号</p>
      </div>
    )
  }

  renderRoles() {
    const { roles } = this.props.onboardingFlowsHr
    if (util.isNull(roles)) return null
    return (
      <div className={style.roles}>
        <FieldBox label={'账号权限'} required>
          <div style={{display: 'table-cell',lineHeight:'30px'}}>
          {
            roles.map((v, i) => (
              <Checkbox 
                disabled={!v.editable}
                active={this.state.fields.roleIds.some(r => r.idValue == v.roleId)}
                onClick={() => {
                  if (v.editable) {
                    this.toggleRoles(v.roleId)
                  }
                }}
                key={i}
                label={v.roleDesc}
              />
            ))
          }
          </div>
        </FieldBox>
      </div>
    )
  }

  renderContractType() {
    return (
      <Select 
        required
        value={this.state.fields.contractType} 
        label={'员工类型'}
        onChange={::this.handleContractTypeChange}>
        <option value="">选择员工类型..</option>
        {
          this.state.contractTypes.map((v, i) => (
            <option key={i} value={v.value}>{ v.label }</option>
          ))
        }
      </Select>
    )
  }

  save() {
    // 检查必填项
    if (['fullName', 'email', /*'citizenId',*/ 'mobilePhone','gender'].some((v) => {
      return this.state.fields[v] === ''
    })) {
      return error('请检查必填项!')
    }

    const { teamId, onboardingTemplateId, contractType, enrollDate, roleIds } = this.state.fields

    if (!onboardingTemplateId) {
      return error('请选择入职模板!')
    }

    if (!teamId) {
      return error('请选择团队!')
    }

    if (!contractType) {
      return error('请选择员工类型!')
    } 

    if (!enrollDate) {
      return error('请选择入职日期!')
    } 

    /*
    if (!roleIds.length) {
      return error('请选择帐号权限!')
    }
    */

    info('创建中..', true)
    this.props.actions.createOnboardingFlow(this.state.fields, () => {
      this.props.router.push('/hr/onboarding/onboarding-flows?hasApproved=0')
      success('创建成功!')
    })
  }

  render() {
    const { fieldMap } = this.props.profileTemplate
    const fields = fieldMap
    const jobTitle = fields.filter(v => v.referenceName === 'jobTitle')[0]
    const jobLevel = fields.filter(v => v.referenceName === 'jobLevel')[0]
    return (
      <div>
        <TitleBar
          back
          label="入职新成员"
        />
        <div>
          <div className={style.list}>
            <div>
              <h2>信息编辑</h2>
              <div>
                <Input 
                  ref="fullName"
                  value={this.state.fields.fullName} 
                  onChange={::this.handleInput('fullName')} 
                  label="新成员姓名" 
                  required
                />
                <Input 
                  ref="email" 
                  name="email" 
                  value={this.state.fields.emailAddress} 
                  onChange={::this.handleInput('emailAddress')} 
                  label="企业邮箱" 
                  required
                />
                <Input 
                  ref="mobilePhone" 
                  name="mobilePhone" 
                  value={this.state.fields.mobilePhone} 
                  onChange={::this.handleInput('mobilePhone')} 
                  label="手机号"
                />
                <Select label={'性别'} required value={this.state.fields.gender} onChange={(e) => this.updateField({ gender: e.target.value })}>
                  <option value="">选择性别...</option>
                  <option value={0}>男</option>
                  <option value={1}>女</option>
                </Select>
                <Input 
                  value={this.state.fields.employeeId} 
                  onChange={::this.handleInput('employeeId')} 
                  label="工号"
                />

                { this.renderOnboardingTemplate() }
                { this.renderJobTitle(jobTitle) }
                { this.renderJobLevel(jobLevel) }
                { this.renderTeams() }
                <label style={{marginLeft:'142px', color: '#7e7f81'}}>
                  <input type={'checkbox'} checked={!!this.state.fields.isTeamAdmin} onChange={e => {this.updateField({isTeamAdmin: +!!e.target.checked})}} />
                  <span style={{marginLeft: '10px'}}>{'设为团队负责人'}</span>
                </label>
                { this.renderContractType() }
                { this.renderReportLine() }
                { this.renderEnrollDate() }
              </div>
              <Button label="新建" onClick={::this.save}/>
            </div>
          </div>
        </div>
      </div>
    )
  }
}
